﻿
var xmlhttp;
var url;
var g_score;
var g_count;
var rank_url='http:\/\/vote4blog.appspot.com\/';

//get_my_url();

//sndReqShowRank();
insert_stub_marks();

function insert_stub_marks(){
	posts = document.getElementById('posts');
	posts.innerHTML = posts.innerHTML.replace(/<\/div>(\s|\r|\n)+<div class="postBody"/g, '</div>\r\n<div class="RankPre"></div>\r\n<div class="postBody"');
	//get url
	posts = document.getElementById('posts');
	list = posts.getElementsByTagName('li');
	
	for(i=0;i<list.length;i++){
		line = list[i].childNodes[1].childNodes[3].childNodes[0];
		the_url = link.href;
		alert('url: '+the_url);
	}
}

function get_my_url(){	
		
	url = window.location.href;
	pos = url.indexOf("?");	
	if (pos>0){  
		url = url.substr(0,pos-1);
	}
	return url;
}
/*
*   className 	the class name 
*   tag 		if no tag , use '*'
*   parent		id of parent element
*/
function getElementsByCls(className, tag, parent){
	parent = parent || document;

	tag = tag || '*';
	if(!(parent = getElementById(parent))){
		return false;
	}
	var tags = (tag =='*' && parent.all) ? parent.all : parent.getElementsByTagName(tag);
	var elements = new Array();	
	className = className.replace(/\-/g, '\\-');
	var regex = new RegExp('(^|\\s)' + className + '(\\s|$)');
	var element;
	var test_method = true;
	for(var i=0,l=tags.length; i<l; i++){
		element = tags[i];
		if(test_method){//true -> use this
			testclassname = element.getAttribute('className');
			if(!testclassname){
				test_method = false;
			}				
		}
		if(!test_method){ //false -> use this
			testclassname = element.getAttribute('class');
		}
		if(regex.test(element.className)){
			elements.push(element);
		}
	}
	return elements;
}

function myXMLHttpRequest() {
	var xmlhttplocal;
   
	/*var msxmlhttp = new Array(
	'Msxml2.XMLHTTP.5.0',
	'Msxml2.XMLHTTP.4.0',
	'Msxml2.XMLHTTP.3.0',
	'Msxml2.XMLHTTP',
	'Microsoft.XMLHTTP');
	for (var i = 0; i < msxmlhttp.length; i++) {
		try {
			xmlhttplocal = new ActiveXObject(msxmlhttp[i]);
		} catch (e) {
			xmlhttplocal = null;	
			continue;
		}
		break;
	}*/
	if(window.XMLHttpRequest) { 
        //针对FireFox,Mozillar,Opera,Safari,IE7,IE8 
        xmlhttplocal = new XMLHttpRequest(); 
        if(xmlhttplocal.overrideMimeType){ 
            xmlhttplocal.overrideMimeType("text/xml"); 
        } 
    }
    else if(window.ActiveXObject){ 
        //针对IE6,IE5.5,IE5 
        //两个可以用于创建XMLHTTPRequest对象的控件名称,保存在一个js数组中 
        //排在前面的版本较新 
        var activexName = ["MSXML2.XMLHTTP","Microsoft.XMLHTTP"]; 
        for(var i = 0;i < activexName.length; i++){ 
            try{ 
                //取出一个控件名进行创建,如果创建成功就终止循环 
                //如果创建失败,会抛出异常,然后可以继续循环,继续尝试创建 
                xmlhttplocal = new ActiveXObject(activexName[i]); 
                break; 
            }catch(e){ 
            } 
        } 
    }  
	
	if(!xmlhttplocal && typeof XMLHttpRequest != "undefined")
		xmlhttplocal = new XMLHttpRequest();
	if (!xmlhttplocal)
		alert("Sigh~~~AJAX错误");
	return xmlhttplocal;
}
//TODO: function which get all positions to insert rank info
function getRankInfoPosArr(){
	/*    'posts' is the containers id  on BLOG BUS
	*/
	return getElementByCls('RankPre','*','posts');
}
function parseURL(str,rule){
	//no filter now
	return str;
}
function sndReqShowRank()
{
/*
	alert("sndReqShowRank called");
	if (url==''){
		alert("empty url!");
		return;
	}
	tmp_url_string = rank_url + 'read?url=' + url;
	alert(tmp_url_string);
	xmlhttp=myXMLHttpRequest();
    xmlhttp.open('GET', tmp_url_string,true);
    xmlhttp.onreadystatechange = handleShowRating;
    xmlhttp.send(null);	
	alert("sndReqShowRank end");
*/
	//fetch all stub pos
	var stubs = getRankInfoPosArr();
	var stub_id = 0;
	var stub_id_str;
	
	for (stub in stubs){
		stub_id_str = 'RankList'+stub_id;
	//read the url from pos
		url_to_rank = parseURL(stub,'');//reserve a rule variant
	//change the id of it
		stub.setAttribute('id', stub_id_str);
	//request a rank result with callback
		
		$(document).ready(
			function(){
			$.getJSON(rank_url+'read?callback=?',{url:url,id:stub_id_str},handleShowRank);
			}
		);	
	//loop
		stub_id = stub_id + 1;
	}
  
}

function handleShowRank(data) {
	//added 20081219,for list ranking
	var id = data.id;//this is the div's id
	var res = data.res;
	var rank = new Number(data.rank);
	var count = data.count;
	
	
	//alert('res = ' + res +';rank = ' + rank + ';count = ' + count);
		
	document.getElementById(id).innerHTML = "<div id=\"Rating\"><div id=\"StarHollow\"><div id=\"StarSolid\"><\/div><a href=\"javascript:Rating(1);\" id=\"Star1\" title=\"太烂了！\"><\/a><a href=\"javascript:Rating(2);\" id=\"Star2\" title=\"不咋地，凑乎吧~\"><\/a><a href=\"javascript:Rating(3);\" id=\"Star3\" title=\"还算是个文章~\"><\/a><a href=\"javascript:Rating(4);\" id=\"Star4\" title=\"这真的是你写的？\"><\/a><a href=\"javascript:Rating(5);\" id=\"Star5\" title=\"哇~~你是我的呕像！\"><\/a><\/div><div id=\"Score\"><\/div><\/div>";
	if (count <= 0)
	{
		document.getElementById("StarSolid").style.width = "0px";
		document.getElementById("Score").innerHTML = "<div id=\"Rating-no\">还没人投票</div>";
	}
	else
	{
		document.getElementById("StarSolid").style.width = rank * 30 + "px";
		document.getElementById("Score").innerHTML = "<div id=\"Rating-show\">平均得分" + rank.toFixed(2) + " ，共投票 " + count + "次</div>";
	}	
}

function Rating(rank)
{
	document.getElementById("Score").innerHTML = "<div id=\"Rating-now\">Ranking, pls wait</div>";

	tmp_url_string = rank_url + 'write';
	$(document).ready(
		function(){
		$.getJSON(tmp_url_string+'?callback=?',{url:url,rank:rank},handleRating);
		}
	);	
	
//	xmlhttp=myXMLHttpRequest();
//    xmlhttp.open('get', url_rank + 'write?url=' + url + '&score=' + rank);
//    xmlhttp.onreadystatechange = handleRating;
//    xmlhttp.send(null);	
}

function handleRating(data) {
	var res = data.res;
	var avg = new Number(data.rank);
	var count = data.count;
	
	if (res == "succ"){
		score = avg.toFixed(2);		
		
		document.getElementById("StarSolid").style.width = score * 30 + "px";		
		document.getElementById("Score").innerHTML = "<div id=\"Rating-Tanks\">投票成功</div>";
		document.getElementById("Score").innerHTML = "<div id=\"Rating-show\">平均得分" + score + "，共投票" + count + "次</div>";
	}else if (res == "dup"){
		document.getElementById("Score").innerHTML = "<div id=\"Rating-already\">您已经为此文章投过一票啦</div>";
	}else if (Rdata=="err"){
		document.getElementById("Score").innerHTML = "<div id=\"Rating-err\">汗，出错了</div>";
	}else{
		document.getElementById("Score").innerHTML = "<div id=\"Rating-err\">汗，又出错了</div>";
	}
}
